//
//  GroupFilesVC.m
//  wanzhaoIM
//
//  Created by liuyuantao on 15/6/1.
//  Copyright (c) 2015年 liuyuantao. All rights reserved.
//

#import "GroupFilesVC.h"
#import "MicroDef.h"
#import "GroupFileCell.h"
#import "CGroupMgr.h"
#import "CXmppRequestMgr.h"
#import "CFileModel.h"
#import "CFileMgr.h"
#import "IMPreviewFileController.h"
#import "ChildHoodService.h"
#import "JKAlertDialog.h"
#import "CFolderMgr.h"
#import "MBProgressHUD+WZ.h"
#import "NetAndAudioModel.h"
#import "UIUtil.h"
#import "UIBarButtonItem+category.h"
#import "CContactMgr.h"
#import "CContactModel.h"
#import "ChildHoodService.h"
#define KSECTIONHEIGHT 20.0f
@interface GroupFilesVC ()<UITableViewDelegate, UITableViewDataSource, GroupFileCellDelegate,UIDocumentInteractionControllerDelegate>
{

    UITableView *_tableView;
    
    
}

@property (nonatomic, strong) NSMutableArray *filesArray;
@property (nonatomic, strong)  UIDocumentInteractionController *doInter;
@end

@implementation GroupFilesVC

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (NSMutableArray *)filesArray
{
    if (_filesArray == nil) {
        _filesArray = [NSMutableArray array];
    }
    return _filesArray;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.navigationController setNavigationBarHidden:NO];
    [self.navigationItem setHidesBackButton:YES];
    
    if (self.group.groupType == 1) {
        [self.navigationItem setNewTitleCenter:@"讨论组文件"];
    } else {
        [self.navigationItem setNewTitleCenter:@"群文件"];
    }
    
    
    
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem BarButtonItemWithImageName:@"call_back" title:@"返回" target:self sel:@selector(back) titleFont:Font18 titleColor:WhiteColor];
    // Do any additional setup after loading the view.
    
//    _progress = [[UIProgressView alloc] init];
//    [_progress setTintColor:RGBCOLOR(0x2c, 0xaa, 0xfe)];
//    _progress.layer.cornerRadius = 1.5f;
//    _progress.layer.masksToBounds = YES;
//    [_progress setTrackTintColor:RGBCOLOR(0xd4, 0xd4, 0xd4)];
//    [self.view addSubview:_progress];
//    UIView *superView = self.view;
//    
//    CGFloat padding = 10.0f;
//    [_progress mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.mas_equalTo(superView).with.offset(padding);
//        make.top.mas_equalTo(superView).with.offset(padding);
//        make.right.mas_equalTo(superView).with.offset(-padding);
//        make.height.mas_equalTo(3);
//        
//    }];
    _tableView = [[UITableView alloc] init];
    _tableView.frame = CGRectMake(0, 0, HARDWARE_SCREEN_WIDTH, HARDWARE_SCREEN_HEIGHT - 64.0f);
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    _tableView.backgroundColor = [UIColor clearColor];
    
    
    self.view.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    
    
    if (self.group) {
        
        __weak typeof (self) weakself = self;
//        CFileMgr *fileMgr = [[CFileMgr alloc] init];
            [[CXmppRequestMgr shareInstance] getGroupFileListWithGroupId:self.group.GroupId successHandel:^(AFHTTPRequestOperation *opration, id responseObject) {
                [UIUtil hideMBProgressViewForView:self.view];
            
//                [fileMgr delFilesByGroupId:self.group.GroupId];
                NSMutableArray *arrayM = [NSMutableArray array];
                    if ([responseObject isKindOfClass:[NSArray class]]) {
                    for (NSDictionary *dict in responseObject) {
                        CFileModel *fileModel = [[CFileModel alloc] init];
                        fileModel.FileName = dict[@"fileName"];
                        fileModel.FileSize = [[dict objectForKey:@"size"] integerValue];
                        fileModel.CreateDate = dict[@"date"];
                        fileModel.GroupId = self.group.GroupId;
                        fileModel.fromUserId = [dict objectForKey:@"userId"];
                        fileModel.serverFileName = dict[@"fullFileName"];
                        [arrayM addObject:fileModel];
//                        [fileMgr insertFile:fileModel];
                    }
                }
//                NSArray *array = [fileMgr loadFilesByGroupId:self.group.GroupId];
                [self.filesArray addObjectsFromArray:[arrayM sortedArrayUsingDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"CreateDate" ascending:NO]]]];
                [weakself configNoticeLabel];
                [_tableView reloadData];
            } filarueHandle:^(AFHTTPRequestOperation *opration, NSError *error) {
            
                [UIUtil hideMBProgressViewForView:self.view];
                
            }];
            [UIUtil addMBProgressViewTitle:@"加载中,请稍后..." inView:self.view alpha:1.0 failureTitle:@"加载失败，请检查网络"];
        }
}

-(void)back
{
    
    [_filesArray enumerateObjectsUsingBlock:^(CFileModel *obj, NSUInteger idx, BOOL *stop) {
        for (NetAndAudioModel *netAndAudio in [CXmppRequestMgr shareInstance].operationArray) {
            if ([netAndAudio.serFileName isEqualToString:obj.serverFileName]) {
                [netAndAudio.operation pause];
            }
        }
        
    }];

    [self.navigationController popViewControllerAnimated:YES ];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
//    [self performSelector:@selector(aa) withObject:nil afterDelay:0.1f];
//    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:5.0 target:self selector:@selector(acton:) userInfo:nil repeats:YES];


}
//bug 8683 fixed by lixu
-(void)configNoticeLabel
{
    
    UILabel *label = [[UILabel alloc] init];
    label.backgroundColor = ClearColor;
    label.textAlignment = NSTextAlignmentCenter;
    label.font = Font16;
    label.textColor = RGBCOLORWITH16COLOR(0xb1b1b1);
    label.text = self.group.groupType == 1?@"还没有讨论组文件":@"还没有群文件";
    label.frame = CGRectMake(0, 0, HARDWARE_SCREEN_WIDTH, Font16.lineHeight);
    label.center = self.view.center;
    [self.view addSubview:label];
    if (self.filesArray.count > 0) {
        label.hidden = YES;
    }
    else
    {
        label.hidden = NO;
    }
}



#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.filesArray.count;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView              // Default is 1 if not implemented
{
    return 1;
}
// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"GroupFileCell";
    GroupFileCell *groupFileCell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (groupFileCell == nil) {
        groupFileCell = [[[NSBundle mainBundle] loadNibNamed:@"GroupFileCell" owner:self options:nil] objectAtIndex:0];
    }
    groupFileCell.groupFileCellDelegate = self;
    groupFileCell.indexPath = indexPath;
    groupFileCell.fileModel = self.filesArray[indexPath.row];
    
    return groupFileCell;
}

- (void)GroupFileCellDidOpenFileWithIndexPath:(NSIndexPath *)indexPath
{
    CFileModel *fileModel = self.filesArray[indexPath.row];
    
    NSString *fileId;
    fileId = fileModel.GroupId;
    NSString *filePath = [[[ChildHoodService defaultService] groupDownLoadFilePathWithGroupId:fileId] stringByAppendingPathComponent:fileModel.serverFileName];
    if ([self checkFileTypeWithFileName:fileModel.FileName]) {
        if (filePath.length > 0) {
            [self transformEncodingFromFilePath:filePath];
            UIDocumentInteractionController *doInter = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:filePath]];
             self.doInter = doInter;
            self.doInter.delegate = self;
            [doInter presentPreviewAnimated:YES];
            
        }

        
    } else {
        if (filePath.length > 0) {
            UIDocumentInteractionController *doInter = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:filePath]];
            doInter.delegate = self;
            self.doInter = doInter;
            [doInter presentOpenInMenuFromRect:self.view.frame inView:self.view animated:YES];
        }

    }
    
}
//bug 8518 fixed by lixu 解决 txt乱码问题
-(void)transformEncodingFromFilePath:(NSString*)filePath
{
    NSStringEncoding *useEncodeing = nil;
    NSString *body = [NSString stringWithContentsOfFile:filePath usedEncoding:useEncodeing error:nil];
    if (body) {
        body = [NSString stringWithContentsOfFile:filePath encoding:0x80000632 error:nil];
    }
    if (body) {
        body = [NSString stringWithContentsOfFile:filePath encoding:0x80000631 error:nil];
    }
    NSData *data = [body dataUsingEncoding:NSUTF16StringEncoding];
    [data writeToFile:filePath atomically:YES];
}
- (void)documentInteractionController:(UIDocumentInteractionController *)controller willBeginSendingToApplication:(NSString *)application
{
//    NSLog(@"heheheh");
}
- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller
{
    return self;
}


- (BOOL)checkFileTypeWithFileName:(NSString *)fileName
{
    NSString *nameStr = [fileName lowercaseString];
    NSString *fileIcon = [UIUtil getFileIconByName:nameStr];
    if ([fileIcon isEqualToString:@"othersIcon"] || fileIcon == nil || [fileIcon isEqualToString:@"rarIcon"]) {
        return NO;
    } else {
        return YES;
    }
}


#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    CGFloat height = 0;
//    switch (section) {
//        case 1:
//            height = KSECTIONHEIGHT;
//            break;
//        case 2:
//            height = KSECTIONHEIGHT;
//            break;
//        case 3:
//            height = KSECTIONHEIGHT;
//            break;
//        default:
//            break;
//    }
    return height;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    CGFloat height = 0;
//    switch (section) {
//        case 3:
//            height = KSECTIONHEIGHT;
//            break;
//        default:
//            break;
//    }
    return height;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section   // custom view for header. will be adjusted to default or specified header height
{
    UIView *headerView = nil;
    if(section == 0)
    {
        return headerView;
    }
    headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 0, tableView.frame.size.width, KSECTIONHEIGHT);
    headerView.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    UIView *beginLine = [[UIView alloc] init];
    beginLine.frame = CGRectMake(0, 0, tableView.frame.size.width, 0.5);
    [beginLine setBackgroundColor:KSEPERATORLINECOLOR];
    [headerView addSubview:beginLine];
    
    UIView *endLine = [[UIView alloc] init];
    endLine.frame = CGRectMake(0, KSECTIONHEIGHT-0.5, tableView.frame.size.width, 0.5);
    [endLine setBackgroundColor:KSEPERATORLINECOLOR];
    [headerView addSubview:endLine];
    
    return headerView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section   // custom view for footer. will be adjusted to default or specified footer height
{
    UIView *headerView = nil;
    if(section != 3)
    {
        return headerView;
    }
    headerView = [[UIView alloc] init];
    headerView.frame = CGRectMake(0, 0, tableView.frame.size.width, 2);
    headerView.backgroundColor = RGBCOLOR(0xf3, 0xf3, 0xf3);
    UIView *beginLine = [[UIView alloc] init];
    beginLine.frame = CGRectMake(0, 0, tableView.frame.size.width, 0.5);
    [beginLine setBackgroundColor:KSEPERATORLINECOLOR];
    [headerView addSubview:beginLine];
    return headerView;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CGFloat height = 90.0f;
    
//    if(indexPath.row == 0 && indexPath.section == 0)
//    {
//        height = 75.0f;
//    }
    return height;
}
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    CContactModel *model = [[[CContactMgr alloc]init] loadCurContact];
    
     CFileModel *fileModel = self.filesArray[indexPath.row];
    if ([fileModel.fromUserId isEqualToString:model.UserID]||[self.group.OwnerId isEqualToString:model.UserID]) {
        return YES;
    }
    return NO;
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    [UIUtil addMBProgressViewTitle:@"正在删除..." inView:self.view alpha:1.0 failureTitle:@"加载失败"];
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        CFileModel *model = self.filesArray[indexPath.row];
        __weak typeof(self) weakself = self;
       [[CXmppRequestMgr shareInstance]deleteGroupFileWithFileName:model.FileName GroupId:model.GroupId dataType:@"file" successHandel:^(AFHTTPRequestOperation *operation, id responseObject) {
           NSDictionary *dic = (NSDictionary*)responseObject;
           if ([[dic objectForKey:@"result"] isEqualToString:@"success"]) {
               [UIUtil hideMBProgressViewForView:weakself.view];
               [MBProgressHUD showSuccess:@"删除成功"];
               [weakself.filesArray removeObject:model];
               [_tableView reloadData];
                NSString *filePath = [[[ChildHoodService defaultService] groupDownLoadFilePathWithGroupId:model.GroupId] stringByAppendingPathComponent:model.serverFileName];
                if (filePath.length > 0)
                {
                    [[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
                }
           }
       } filarueHandle:^(AFHTTPRequestOperation *operation, NSError *error) {
           [UIUtil hideMBProgressViewForView:weakself.view];
           [MBProgressHUD showError:@"删除失败"];
       }];
    }
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    CATransform3D transform3D = CATransform3DMakeRotation(M_PI_2, 0.0, 1.0, 1.0);
         cell.alpha = 0.0;
         cell.layer.transform = transform3D;
         cell.layer.anchorPoint = CGPointMake(0.0, 0.5); // 设置锚点位置；默认为中心点(0.5, 0.5)
    [UIView animateWithDuration:0.5 animations:^{
            cell.alpha = 1.0;
            cell.layer.transform = CATransform3DIdentity;
                CGRect rect = cell.frame;
                rect.origin.x = 0.0;
                 cell.frame = rect;
           }];
}


@end
